// lib/models/sina_stock_model.dart
class StockModel {
  final String name;
  final String symbol;
  final double currentPrice;
  final double yesterdayClose;
  final double todayOpen;
  final double high;
  final double low;
  final int volume;
  final double amount;
  final DateTime date;
  final DateTime time;

  StockModel({
    required this.name,
    required this.symbol,
    required this.currentPrice,
    required this.yesterdayClose,
    required this.todayOpen,
    required this.high,
    required this.low,
    required this.volume,
    required this.amount,
    required this.date,
    required this.time,
  });

  // 计算涨跌幅
  double get changePercent {
    if (yesterdayClose == 0) return 0;
    return ((currentPrice - yesterdayClose) / yesterdayClose) * 100;
  }

  // 计算涨跌额
  double get changeAmount {
    return currentPrice - yesterdayClose;
  }

  // 从新浪API返回的数据解析
  factory StockModel.fromSinaData(String symbol, String data) {
    final parts = data.split(',');

    if (parts.length < 32) {
      // 返回一个空的股票模型
      return StockModel(
        name: symbol,
        symbol: symbol,
        currentPrice: 0,
        yesterdayClose: 0,
        todayOpen: 0,
        high: 0,
        low: 0,
        volume: 0,
        amount: 0,
        date: DateTime.now(),
        time: DateTime.now(),
      );
    }

    try {
      // 修正日期和时间解析
      DateTime date;
      DateTime time;

      try {
        date = DateTime.parse(parts[30]);
      } catch (e) {
        date = DateTime.now();
      }

      try {
        time = DateTime.parse('${parts[30]} ${parts[31]}');
      } catch (e) {
        time = DateTime.now();
      }

      return StockModel(
        name: parts[0].isNotEmpty ? parts[0] : symbol,
        symbol: symbol,
        currentPrice: double.tryParse(parts[3]) ?? 0,
        yesterdayClose: double.tryParse(parts[2]) ?? 0,
        todayOpen: double.tryParse(parts[1]) ?? 0,
        high: double.tryParse(parts[4]) ?? 0,
        low: double.tryParse(parts[5]) ?? 0,
        volume: int.tryParse(parts[8]) ?? 0,
        amount: double.tryParse(parts[9]) ?? 0,
        date: date,
        time: time,
      );
    } catch (e) {
      // 解析失败时返回默认值
      return StockModel(
        name: symbol,
        symbol: symbol,
        currentPrice: 0,
        yesterdayClose: 0,
        todayOpen: 0,
        high: 0,
        low: 0,
        volume: 0,
        amount: 0,
        date: DateTime.now(),
        time: DateTime.now(),
      );
    }
  }
}